<?php
/**
 * _array.class
 *
 * script
 *
 * @version:	0.1a
 * @package:	global
 * @author:	alex_ez
 * @created:	16.02.2009 15:02:27
 *
 * @copyright:	(c) 2009 alex <qfox@ya.ru> yaroshevich aka alex_ez. All rights reserved.
 */



final class _a
{
	static public function flat( $A, $tkey, $tvalue = null )
	{
		if( !is_array( $A ) ) return null;
		
		$_r = array( );
		
		foreach( $A as $k => $v )
		{
			$__nv = is_array( $tvalue )
				? array_intersect_key( $v, array_flip( array_values( $tvalue ) ) )
				: ( is_null( $tvalue ) ? $v : ( ($tvalue == '$') ? $k : $v[ $tvalue ] ) );
			
			if( isset($v[ $tkey ]) || $tkey=='$' )
			{
				$__nk = ($tkey == '$') ? $k : $v[ $tkey ];
				$_r[$__nk] = $__nv;
			}
			elseif( empty( $tkey ) )
			{
				$_r[] = $__nv;
			}
		}
		
		return $_r;
	}
	
	static public function joinf( $d = null, $a, $t = null )
	{
		if( !is_array( $a ) || empty( $a ) ) return 'null';
		
		if( is_null( $d ) || !mb_strlen($d) || !$d ) $d = '; ';
		if( is_null( $t ) || !mb_strlen($t) || !$t ) $t = '%k:%v';
		
		$t = str_replace( array('%k','%v'), array('%1$s','%2$s'), $t );
		$r = '';
		foreach( $a as $k=>$v ) $r .= sprintf( $t, $k, $v ) . $d;
		
		return mb_substr( $r, 0, -mb_strlen( $d ) );
	}
	
	static public function simplify( $A, $backlevel = 0 ) //Array, parentKey
	{
		$r = array( );
		foreach( $A as $k => $v )
		if( is_array( $v ) ) {
			
			$vbacklevel = 0;
			$vback = $v;
			while( $vback = reset( $vback ) )
			{
				$vbacklevel++;
				//var_dump( $vback, is_array( $vback ), $vbacklevel );
				if( $vbacklevel <= $backlevel ) {
					$r[$k] = $v;
					continue 2;
				}
				if( !is_array( $vback ) ) break;
			}
			
			
			foreach( self::simplify( $v ) as $_k => $_v )
				$r["{$k}[{$_k}"] = $_v;
		}
		else $r[$k] = $v;
		
		$rk = array_map( create_function( '$a', '$k=""; $a=explode("[",str_replace("]","",$a)); $k=array_shift($a); if( sizeof($a) ) $k .= "[".join("][",$a)."]"; return $k;' ), array_keys( $r ) );
		$rv = array_values( $r );
		$r = array( );
		
		if( count( $rk ) && count( $rk ) == count( $rv ) )
			$r = array_combine( $rk, $rv );
		
		return $r;
	}
}

?>